package com.bbs.service.impl;

import com.bbs.dao.PostDao;
import com.bbs.dao.UserDao;
import com.bbs.entity.Page;
import com.bbs.entity.Post;
import com.bbs.service.PostService;
import com.bbs.service.ReplyService;
import com.bbs.utils.MyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service("postService")
public class PostServiceImpl implements PostService {
    @Autowired
    private PostDao postDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private ReplyService replyService;
    /**
     * 查询发帖列表
     * @param curPage 查询多少条
     * @return
     */
    public Page<Post> findByPage(int curPage) {
        //每页记录数
        int limit = 5;
        //从哪开始.假设curPage=2,即从第二页开始查，那么offset=(2-1)*5=5,即从第五条记录开始查
        int offset = (curPage-1) * limit;
        //获得总记录数，总页数
        int allCount = postDao.selectPostCount();// 记得在相应的dao增加该方法
        int allPage = 0;
        if (allCount <= limit) {
            allPage = 1;
        } else if (allCount % limit == 0) {
            allPage = allCount / limit;
        } else {
            allPage = allCount / limit + 1;
        }
        //帖子数据列表
        List<Post> postList = postDao.findByPage(offset,limit);
        // 封装分页对象信息并返回给控制器
        Page<Post> pageInfo = new Page<>(allPage,curPage);
        pageInfo.setList(postList);// 给分页对象设置list列表数据
        return pageInfo;
    }

    @Override
    public int publishPost(Post post) {
        post.setPublishTime(MyUtil.formatDate(new Date()));
        post.setReplyTime(MyUtil.formatDate(new Date()));
        //个人页面发帖数量
        userDao.updatepostCount(post.getUid());
        return postDao.savePost(post);
    }

    @Override
    public Post getPostByPid(int pid) {
        //更新浏览数
        postDao.updataScanCount(pid);
        return postDao.getPostByPid(pid);
    }
//个人页面
    @Override
    public List<Post> getPostList(int uid) {
        return postDao.getPostList(uid);
    }

/*
*楼中楼回复评论
*/
@RequestMapping("/comment")
    public String comment(int pid, int rid, String content, HttpSession session){
    Integer uid = (Integer)session.getAttribute(("uid"));
    if (uid == null){
        return "redict:toLogin";
    }
    int sessionUid = (int) session.getAttribute("uid");
    replyService.comment(pid,sessionUid,rid,content);
    return "redirect:toPost.do?pid="+pid;
}
}
